package com.directorio.controller.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.directorio.modelo.bean.Administrador;
import com.directorio.modelo.bean.Alumno;
import com.directorio.modelo.bean.Alumno_Capacitacion;
import com.directorio.modelo.bean.Alumno_Experiencia;
import com.directorio.modelo.bean.Alumno_Formacion;
import com.directorio.modelo.bean.Alumno_Habilidad;
import com.directorio.modelo.bean.Alumno_Requerimiento;
import com.directorio.modelo.bean.Dato_Tipo;
import com.directorio.modelo.bean.Empresa;
import com.directorio.modelo.bean.Menu;
import com.directorio.modelo.bean.Persona;
import com.directorio.modelo.service.AlumnoService;
import com.directorio.modelo.service.EmpresaService;
import com.directorio.modelo.service.MenuService;
import com.directorio.modelo.utiles.pojo.JsonData;
import com.directorio.controller.FrontEnd;
import com.google.gson.Gson;

public class UsuariosController extends HttpServlet {

	private static UsuariosController usuarioIntegration;	
    private static final long serialVersionUID = 1L;
    private MenuService menu = null;
    private AlumnoService alumno = null;
    private HttpServletRequest request;
    private Gson json = null;
    public static EmpresaService empresaService;
    private ServletConfig conf;

    public UsuariosController() {
        super();
        requestContext();
    }
    public void init(ServletConfig config) throws ServletException {
    	this.conf = config;
		super.init(config);
		requestContext();
	}
    
    public static UsuariosController getInstance(){
    	if(UsuariosController.usuarioIntegration==null){
    		usuarioIntegration = new UsuariosController();
    	}
    	return usuarioIntegration;
    }

    private void requestContext() {
        System.out.println("Cargando Logica Usuarios...!");
        alumno = (AlumnoService) FrontEnd.CONTEXT.getBean("alumnoService");
        menu = (MenuService) FrontEnd.CONTEXT.getBean("menuService");
        empresaService = (EmpresaService) FrontEnd.CONTEXT.getBean("empresaService");
        json = new Gson();
        System.out.println("Logica Usuarios Cargado Correctamente...!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        procestServlet(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        procestServlet(request, response);
    }

    private void procestServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.request = request;
        String ret = "";
        boolean band = false;
        try {
            int op = Integer.parseInt(request.getParameter("opt"));
            switch (op) {
                case 1:ret = this.getAlumnoAll();break;
                case 2:ret = this.getAlumno();break;
                case 3:	band = true;break;
                case 4: ret = this.insertAlumno();break;                
                case 9: ret = this.eliminarExperiencia();break;
                case 10: ret = this.insertExperiencia();break;
                case 11: ret = this.modificarExperiencia();break;
                case 12: ret = this.insertCapacitacion();break;
                case 13: ret = this.modificarCapacitacion();break;
                case 19: ret = this.eliminarCapacitacion();break;
                case 14: ret = this.insertHabilidad();break;
                case 15: ret = this.insertFormacion();break;
                case 16: ret = this.modificarFormacion();break;
                case 17: ret = this.eliminarFormacion();break;
                case 18: ret = this.modificarDatosAlumno();break;
                case 30: ret = this.getHabilidades();break;
                case 31: ret = this.getExperiencias();break;
                case 32: ret = this.getCapacitaciones();break;
                case 33: ret = this.getFormaciones();break;
                case 40: ret = this.updatePwd();break;
                case 41: ret = this.getBbuscarOferta();break;
                case 42: ret = this.getOfertasPersonales();break;
                case 43: ret = this.asistirOfertasPersonal();break;
                case 61:ret = this.getMenu();break;
                case 62:ret = this.getSubMenu();break;
            }
        } catch (NumberFormatException ex) {
        	System.out.println("Error->");
        }
        if (band && Boolean.parseBoolean(request.getParameter("_DRTR_WB_LGN"))) {
            HttpSession sesion = request.getSession();
            String cod = this.request.getParameter("cod");
            String pwd = this.request.getParameter("pwd");
            Dato_Tipo dat = null;
            try {
                dat = this.alumno.validLogin(cod, pwd);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (Integer.parseInt(dat.getCod()) == 0) {
                sesion.setAttribute("error", dat);
                if(cod.length()==8){
                	response.getWriter().print("cpanel.mv");
                }else{
                	response.getWriter().print("login.mv");
                }                
            } else if (Integer.parseInt(dat.getCod()) == 4) {
                    try {
                        Empresa emp = this.empresaService.obtenerEmpresa(cod);
                        System.out.println(emp.toString());
                        sesion.setAttribute("empresa", emp);
                        response.getWriter().print("empresa-inicio.mv");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(dat.toString());
                } else if (Integer.parseInt(dat.getCod()) == 1) {
                        try {
                            Alumno al = this.alumno.obtenerAlumno(cod);
                            sesion.setAttribute("alumno", al);
                            response.getWriter().print("alumno-egresado-inicio.mv");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else if (Integer.parseInt(dat.getCod()) == 6) {
                            try {
                                Administrador admin = this.alumno.obtenerAdministrador(cod);
                                sesion.setAttribute("administrador", admin);
                                response.getWriter().print("administrador-inicio.mv");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
        }
        response.getWriter().print(ret);
    }

    private String eliminarCapacitacion() {
    	int op = 0;
		Alumno_Capacitacion capac = new Alumno_Capacitacion();
		HttpSession ses = this.request.getSession();		
		try{
			capac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			capac.setCod_itm(this.request.getParameter("cod_itm"));
			op = alumno.modificarAlumnoCapacitacion(capac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}
	private String asistirOfertasPersonal() {
    	int op = 0;
		Alumno_Requerimiento requer = new Alumno_Requerimiento();
		HttpSession ses = this.request.getSession();		
		try{
			requer.setCd_un(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			requer.setId_rq(this.request.getParameter("requer"));
			requer.setRuc(this.request.getParameter("ruc"));
			requer.setPret(this.request.getParameter("pret"));
			op = alumno.asistirAlumnoARequerimiento(requer);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}
	private String getOfertasPersonales() {
    	String ret = "";
        List listReq = null;
        Map map = new HashMap();
        HttpSession ses = this.request.getSession();
        String ruc = "";
        try{
        	map.put("_st_rq",this.request.getParameter("s_of"));
        	map.put("_st_al",this.request.getParameter("s_al"));
        	map.put("_cd_un",((Alumno)ses.getAttribute("alumno")).getCod_alum());        	
            listReq = empresaService.getBusquedadRequerimientosFromAlum(map);;
            ret = json.toJson(listReq);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            ret = null;
        }
        return ret;
	}
	private String getBbuscarOferta() {
    	String ret = "";
        List listReq = null;
        Map map = new HashMap();
        HttpSession ses = this.request.getSession();
        String ruc = "";
        try{
        	if(this.request.getParameter("esc")!=null){
        		map.put("_esc",this.request.getParameter("esc"));
        	}
        	if(this.request.getParameter("dsc")!=null){
        		map.put("_dsc",this.request.getParameter("dsc"));
        	}       	
        	map.put("_std","02");
            listReq = empresaService.obtenerBusquedadRequerimientos(map);
            ret = json.toJson(listReq);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            ret = null;
        }
        return ret;
	}
	private String insertAlumno() {
    	Dato_Tipo dat = null;
    	Map map = new HashMap();
    	Persona per = new Persona();
    	Alumno alu = new Alumno();
        try {
        	per.setDni(this.request.getParameter("dni"));
        	per.setNomb_pers(this.request.getParameter("nmb"));
        	per.setApe_paterno_pers(this.request.getParameter("ape"));
        	per.setDir(this.request.getParameter("direc"));
        	per.setEma_pers(this.request.getParameter("email"));
        	per.setCel(this.request.getParameter("fno"));
        	alu.setPersona(per);
        	alu.setCod_alum(this.request.getParameter("cod_un"));
        	alu.setEscu(this.request.getParameter("escu"));
        	alu.setTip_alum(this.request.getParameter("cod_tp"));        	
            dat = this.alumno.agregarAlumno(alu);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json.toJson(new JsonData(dat));
	}
	private String getFormaciones() {
    	List<Alumno_Formacion> formaciones = null;
    	Map map = new HashMap();
		HttpSession ses = this.request.getSession();		
		String ret = "";
		try{
			map.put("_cod", ((Alumno)ses.getAttribute("alumno")).getCod_alum());
			map.put("_tip", Integer.parseInt(this.request.getParameter("tip")));
			formaciones = alumno.obtenerFormaciones(map);
			ret = json.toJson(formaciones);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return ret;
	}

	private String modificarDatosAlumno() {
    	int op = 0;
		Alumno_Formacion formac = new Alumno_Formacion();
		HttpSession ses = this.request.getSession();
		Map map = new HashMap();
		try{
			map.put("_cod",((Alumno)ses.getAttribute("alumno")).getCod_alum());
			map.put("_val",this.request.getParameter("val"));
			map.put("_op",Integer.parseInt(this.request.getParameter("opc")));
			op = alumno.modificarDatosAlumno(map);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String updatePwd() {
    	Dato_Tipo dat = null;
    	Map map = new HashMap();
    	HttpSession ses = this.request.getSession();
        try {
        	String id = "";
        	if(ses.getAttribute("empresa")!=null){
        		id = ((Empresa)ses.getAttribute("empresa")).getRuc();
        	}else if(ses.getAttribute("alumno")!=null){
        		id = ((Alumno)ses.getAttribute("alumno")).getCod_alum();
        	}else if(ses.getAttribute("administrador")!=null){
        		id = ((Administrador)ses.getAttribute("administrador")).getCod();
        	}
        	map.put("_id", id);
        	map.put("_pw_vi", this.request.getParameter("pwd_ol"));
        	map.put("_pw_nw", this.request.getParameter("pwd_nw"));        	
            dat = this.alumno.cambiarContrasena(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json.toJson(new JsonData(dat));
	}

	private String getCapacitaciones() {
    	List<Alumno_Capacitacion> capacitaciones = null;
		HttpSession ses = this.request.getSession();
		String ret = "";
		try{
			capacitaciones = alumno.obtenerCapacitaciones(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			ret = json.toJson(capacitaciones);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return ret;
	}

	private String getExperiencias() {
    	List<Alumno_Experiencia> experiencias = null;
		HttpSession ses = this.request.getSession();
		String ret = "";
		try{
			experiencias = alumno.obtenerExperiencias(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			ret = json.toJson(experiencias);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return ret;
	}

	private String getHabilidades() {
		List<Alumno_Habilidad> habilidades = null;
		HttpSession ses = this.request.getSession();
		String ret = "";
		try{
			habilidades = alumno.obtenerHabilidades(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			ret = json.toJson(habilidades);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return ret;
	}

	private String eliminarFormacion() {
    	int op = 0;
		Alumno_Formacion formac = new Alumno_Formacion();
		HttpSession ses = this.request.getSession();		
		try{
			formac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			formac.setCod_itm(this.request.getParameter("cod_itm"));
			op = alumno.elminarAlumnoFormacion(formac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String modificarFormacion() {
		int op = 0;
		Alumno_Formacion formac = new Alumno_Formacion();
		HttpSession ses = this.request.getSession();		
		try{
			formac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			formac.setCod_tip(this.request.getParameter("cod_tip"));
			formac.setCod_itm(this.request.getParameter("cod_itm"));
			formac.setNmb_ins(this.request.getParameter("nom_ins"));
			formac.setDsc_ins(this.request.getParameter("dsc_ins"));
			formac.setFec_ini(this.request.getParameter("fec_ini"));
			formac.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.modificarAlumnoFormacion(formac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String insertFormacion() {
		int op = 0;
		Alumno_Formacion formac = new Alumno_Formacion();
		HttpSession ses = this.request.getSession();		
		try{
			formac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			formac.setCod_tip(this.request.getParameter("cod_tip"));
			formac.setNmb_ins(this.request.getParameter("nom_ins"));
			formac.setDsc_ins(this.request.getParameter("dsc_ins"));
			formac.setFec_ini(this.request.getParameter("fec_ini"));
			formac.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.agregarAlumnoFormacion(formac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String insertHabilidad() {
		int op = 0;
		Alumno_Habilidad habil = new Alumno_Habilidad();
		HttpSession ses = this.request.getSession();		
		try{
			habil.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());			
			habil.setCod_hab(this.request.getParameter("cod_hab"));
			op = alumno.agregarAlumnoHabilidad(habil);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String modificarCapacitacion() {
    	int op = 0;
		Alumno_Capacitacion capac = new Alumno_Capacitacion();
		HttpSession ses = this.request.getSession();		
		try{
			capac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			capac.setCod_itm(this.request.getParameter("cod_itm"));
			capac.setTip_cod_cap(this.request.getParameter("tip_cap"));
			capac.setNom_cap(this.request.getParameter("nom_cap"));
			capac.setIns_cap(this.request.getParameter("ins_cap"));
			capac.setDsc_cap(this.request.getParameter("dsc_cap"));
			capac.setFec_ini(this.request.getParameter("fec_ini"));
			capac.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.modificarAlumnoCapacitacion(capac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String insertCapacitacion() {
		int op = 0;
		Alumno_Capacitacion capac = new Alumno_Capacitacion();
		HttpSession ses = this.request.getSession();		
		try{
			capac.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			capac.setTip_cod_cap(this.request.getParameter("tip_cap"));
			capac.setNom_cap(this.request.getParameter("nom_cap"));
			capac.setIns_cap(this.request.getParameter("ins_cap"));
			capac.setDsc_cap(this.request.getParameter("dsc_cap"));
			capac.setFec_ini(this.request.getParameter("fec_ini"));
			capac.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.agregarAlumnoCapacitacion(capac);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String modificarExperiencia() {
    	int op = 0;
		Alumno_Experiencia exper = new Alumno_Experiencia();
		HttpSession ses = this.request.getSession();		
		try{
			exper.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			exper.setCod_itm(this.request.getParameter("cod_itm"));
			exper.setNmb_emp(this.request.getParameter("emp_nom"));
			exper.setCrg_emp(this.request.getParameter("emp_car"));
			exper.setFec_ini(this.request.getParameter("fec_ini"));
			exper.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.modificarAlumnoExperiencia(exper);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}
	private String eliminarExperiencia() {
    	int op = 0;
		Alumno_Experiencia exper = new Alumno_Experiencia();
		HttpSession ses = this.request.getSession();		
		try{
			exper.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			exper.setCod_itm(this.request.getParameter("cod_itm"));
			op = alumno.eliminarAlumnoExperiencia(exper);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}

	private String insertExperiencia() {
		int op = 0;
		Alumno_Experiencia exper = new Alumno_Experiencia();
		HttpSession ses = this.request.getSession();		
		try{
			exper.setCod_unp(((Alumno)ses.getAttribute("alumno")).getCod_alum());
			exper.setNmb_emp(this.request.getParameter("emp_nom"));
			exper.setCrg_emp(this.request.getParameter("emp_car"));
			exper.setFec_ini(this.request.getParameter("fec_ini"));
			exper.setFec_fin(this.request.getParameter("fec_fin"));
			op = alumno.agregarAlumnoExperiencia(exper);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return json.toJson(new JsonData(op != 0 ? "ok" : null));
	}
	private String getSubMenu() {
        int tipo = Integer.parseInt(this.request.getParameter("tipo"));
        int menu = Integer.parseInt(this.request.getParameter("menu"));
        String ret = "";
        try {
            List<Menu> list = this.menu.obtenerSubMenu(tipo, menu);
            ret = json.toJson(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    private String getMenu() {
        int codigo = Integer.parseInt("" + this.request.getParameter("tipo"));
        String ret = "";
        try {
            List<Menu> list = this.menu.obtenerMenu(codigo);
            ret = json.toJson(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    private String getAlumnoAll() {
        String ret = "";
        Map map = new HashMap();
        try {
            map.put("_std",this.request.getParameter("std"));
            map.put("_cod",this.request.getParameter("cod"));
            map.put("_ap",this.request.getParameter("ape"));
            map.put("_nmb",this.request.getParameter("nmb"));
            map.put("_fac", this.request.getParameter("fac"));
            List<Alumno> list = this.alumno.obtenerAlumnoAll(map);
            ret = json.toJson(list);
        } catch (Exception ex) {
            json = null;
            ex.printStackTrace();
        }
        return ret;
    }

    private String getAlumno() {
    	HttpSession ses = this.request.getSession();
        String codigo = "";
        String ret = "";
        try {
        	codigo = ""+((Alumno)ses.getAttribute("alumno")).getCod_alum();
            Alumno alumno = this.alumno.obtenerAlumno(codigo);
            ret = json.toJson(alumno);
        }catch(Exception ex) {
            ret = "";
            ex.printStackTrace();
        }
        return ret;
    }
    
    public String getSubMenuInvoker(int tipo, int menu) {
    	String ret = "";
        List<Menu> list = null;
        try {
            list = this.menu.obtenerSubMenu(tipo, 0);
            ret = json.toJson(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    public List<Menu> getMenuInvoker(int codigo) {
        List<Menu> list = null;
        try {
            list = this.menu.obtenerMenu(codigo);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }
}
